package com.boruan.qq.zxgylibrary.ui.activities;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.boruan.qq.zxgylibrary.R;
import com.boruan.qq.zxgylibrary.R2;
import com.boruan.qq.zxgylibrary.base.BaseActivity;
import com.boruan.qq.zxgylibrary.service.model.PayResultBean;
import com.boruan.qq.zxgylibrary.service.presenter.PayPresenter;
import com.boruan.qq.zxgylibrary.service.view.PayView;
import com.boruan.qq.zxgylibrary.utils.CustomDialog;
import com.convenient.qd.core.constant.Constant;
import com.convenient.qd.core.utils.UMEventUtil;

import butterknife.BindView;
import butterknife.OnClick;

import static com.boruan.qq.zxgylibrary.ui.activities.ConfirmOrderActivity.PAY_FAILED_RESULT_CODE;
import static com.boruan.qq.zxgylibrary.ui.activities.ConfirmOrderActivity.PAY_SUCCESS_RESULT_CODE;

/**
 * Created by 崔琦 on 2019/9/18.
 * des: 支付宝web页支付
 */

public class GYAlipayWebActivity extends BaseActivity implements PayView{
    @BindView(R2.id.ll_add_web)
    LinearLayout llAddWeb;

    private CustomDialog dialog;
    private String payUrl;
    private String tradeId;
    private boolean isFirst = true;
    private PayPresenter payPresenter;

    @Override
    protected int getLayoutId() {
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        return R.layout.drug_activity_alipy_web;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        if (getIntent() != null){
            payUrl = getIntent().getStringExtra("url");
            tradeId = getIntent().getStringExtra("tradeId");
        }

        payPresenter = new PayPresenter(this);
        payPresenter.onCreate();
        payPresenter.attachView(this);

        dialog = new CustomDialog(this, R.style.CustomDialog);
        dialog.show();
        initCommonWeb(payUrl);
    }
    private PayResultBean.ResultBean mPayResultBean;
    @Override
    protected void onRestart() {
        super.onRestart();
        isFirst = false;
        payPresenter.getPayResultInfo(tradeId);
    }

    /**
     * 初始化web
     */
    @SuppressLint("JavascriptInterface")
    private void initCommonWeb(final String richText){
        commonWeb.loadUrl(richText);
        commonWeb.addJavascriptInterface(GYAlipayWebActivity.this, "control");
        commonWeb.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                dialog.dismiss();
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);

            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                final Activity context = GYAlipayWebActivity.this;
                if (url.startsWith("alipays://") && isFirst){
                    try {
                        Intent intent = Intent.parseUri(url,Intent.URI_INTENT_SCHEME);
                        intent.addCategory("android.intent.category.BROWSABLE");
                        intent.setComponent(null);
                        context.startActivity(intent);
                    }catch (Exception e){
                        Toast.makeText(context, "未安装支付宝！", Toast.LENGTH_SHORT).show();
                    }
                }else {
                    view.loadUrl(url);
                }
                return true;

            }
        });
        llAddWeb.addView(commonWeb);
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }

    @Override
    public void getPayResultSuccess(PayResultBean.ResultBean payResultBean) {
        UMEventUtil.onOrderEventObject(this,"2001009", Constant.sceneId);
        mPayResultBean = payResultBean;
        //先调接口判断一下订单状态是1还是21
        payPresenter.getOrderDetailInfo(tradeId);

    }

    @Override
    public void getPayResultFailed(String msg) {
        UMEventUtil.onOrderEventObject(this,"2001010", Constant.sceneId);
        if(TextUtils.isEmpty(msg)){
            return;
        }
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void getOrderDetailSuccess(int orderStatus) {
        Intent intent = new Intent();
        intent.putExtra("orderStatus",orderStatus);
        if (mPayResultBean.isPay()){//表示已经付完款了
            setResult(PAY_SUCCESS_RESULT_CODE,intent);
            finish();
        }else {//没有付款
            setResult(PAY_FAILED_RESULT_CODE,intent);
            finish();
        }
    }

    @Override
    public void getOrderDetailFailed(String msg) {
        if(TextUtils.isEmpty(msg)){
            return;
        }
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && commonWeb.canGoBack()) {
            commonWeb.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }



    @Override
    protected void onDestroy() {
        Log.i("测试","ondes");
        if (commonWeb != null) {
            //加载null内容
            commonWeb.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            //清除历史记录
            commonWeb.clearHistory();
            //移除WebView
            ((ViewGroup) commonWeb.getParent()).removeView(commonWeb);
            //销毁VebView
            commonWeb.destroy();
            //WebView置为null
            commonWeb = null;
        }
        super.onDestroy();
    }
    @OnClick(R2.id.iv_back)
    public void onViewClicked() {
        finish();
    }

}
